/**
 * 角色管理设置
 * 
 * @version 1.0.0
 * @author yangyibao
 */
var powerTable;//权限数据表
var pro="";
$(function () {
	$.post("../user/queryUserAllData",function(data){
		var str = ""
			$("#personInfoDiv .modal-title").html('<span id="lblAddTitle" style="font-weight:bold;color:white"> 添加人员</span>');
		for(var i = 0; i < data.length; i++){
			str = str + "<option value='"+ data[i].userId +"'>"+data[i].userName+"("+data[i].userId+")"+"</option>" 
		}
		str = str + "</select>";
		var personInfoDiv = "<div class='span12'>  <div class='portlet box green'>" +
		                    "<div class='caption'></div>"+
		                    "<div class='portlet-body form'><form action='#' class='form-horizontal'><div class='control-group'>"+
		                    "<label class='control-label'></label> <div class='controls'><input type='hidden'>"+
		                    "<select multiple='multiple' id='my_multi_select1' name='my_multi_select1[]'>";
		personInfoDiv = personInfoDiv + str + "</div></div></form></div></div></div>"; 
		$("#personInfoDiv .row-fluid").html(personInfoDiv); 
		
	});
	
	powerTable = $('#roleDataTables').DataTable({
		"bProcessing": true,
		"bLengthChange":true,
		"bServerSide": true,//服务端数据处理
		"bFilter": false,//无搜索 
		/*"iDisplayLength":8,//默认数据条数
		 */           "bSort": false,//排序功能
		 "pagingType":"full_numbers",
		 "sAjaxSource": "../system/groupVO/queryGroupVOPageList",//后端服务地址
		 "fbServerData":function(sSource,aDataSet){$.ajax({"dataType":"json","type":"GET","url":sSource,"data":aDataSet});},
		 "aoColumns":[{"mDataProp":"groupId"},{"mDataProp":"groupName"},{"mDataProp":"groupMark"},{"mDataProp":"groupTimestamp"},{"mDataProp":"groupId"}],
		 "aoColumnDefs":[
		                 {"aTargets":[4],"mRender":function(data,type,full){
		                	 var operation="<div class='btn-group'><a class='btn btn-operate-left' href='#' data-toggle='dropdown'><i class='icon-user'></i> 操作</a><a href='#' type='button' class='btn btn-operate-right dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'><span class='caret'></span></a>"
		                		 operation+="<ul class='dropdown-menu'>";
		                	 operation+="<li><a href='#' id='getPermissions' data-id='"+data+"' data-value='"+full.groupName+"'> 修改功能菜单权限</a></li>";
		                	 operation+="<li><a href='#' id='uptPerson' data-id='"+data+"' > 修改该组成员</a></li>";
		                	 operation+="<li><a href='#' id='uptRole' data-id='"+data+"' data-name='"+full.groupName+"' data-desc='"+full.groupMark+"'>编辑群组基本信息</a></li>";
		                	 operation+="<li><a href='#' id='dltRole' data-id='"+data+"' data-name='"+full.groupName+"'>删除群组</a></li>";
		                	 operation+="</ul></div>";
		                	 return operation;
		                 }
		                 }],
		                 "oLanguage":{"sUrl": "../resources/assets/plugins/dataTables/txt/page.txt"},
		                 "initComplete":function () {
		                	 $('#roleDataTables_length').find('select').selectpicker('render');
		                	 $('#roleDataTables_length').find('select').selectpicker('refresh');
		                	 $('#roleDataTables_length').find('.btn-group').css('width','auto');
		                	 $('#roleDataTables_length').find('.btn').css('background-color','#fff');
		                	 $('#roleDataTables_length').find('.btn').css('border','#d8d8d8 solid 1px')
		                 }
	});

	//绑定查看功能模块
	$('#roleDataTables tbody').on('click','#getPermissions',function(){
		var groupId = $(this).attr("data-id");
		var setting = {
				treeId:'tree',
				check:{enable: true},
				data:{
					simpleData:{enable : true,idKey : "permissionId",pIdKey : "permissionParentId",rootPId:null},
					key:{name:"permissionName",checked: "ext1"}
				},
				callback:{
					onCheck: zTreeOnCheck
				}
		};
		$.post("../system/groupVO/queryPermissionList",{groupId:groupId},function(data){
			var zTree = $.fn.zTree.init($("#treeDemo"), setting,data);
			var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
			treeObj.expandAll(true);
		});

		//treeNode点击事件处理，若节点发生变化，修改按钮变为可用状态；否则为不可用状态 
		function zTreeOnCheck(event, treeId, treeNode){
			var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
			var nodes = treeObj.getChangeCheckedNodes();
			for(var i=0;i<nodes.length;i++){
				nodes[i].ext2 = groupId;
			}
			if(nodes !=''){$("#uptBtn").attr("disabled",false);}
			else{$("#uptBtn").attr("disabled",true);}
		};

		$("#roleBaseInfoDiv").modal("show");
	});

//	JSON.stringify(nodes),
	//确定按钮修改角色权限
	$("#uptBtn").click(function(){
		var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
		var nodes = treeObj.getChangeCheckedNodes();
	//	console.log(JSON.stringify(nodes));
		$.ajax({
			url:"../system/groupVO/modifyPermissions",
			type: "POST",
			contentType:"application/json",
			dataType: "json",
			data:JSON.stringify(nodes),
			success:function(data){
				swal("成功!","角色功能菜单权限变更成功!", "success");}
		});
	});

	//删除角色操作
	$('#roleDataTables tbody').on('click','#dltRole',function(){
		var name = $(this).attr("data-name");
		var id = $(this).attr("data-id");
		confirm("您确定删除["+name+"]群组？", function(isConfirm){if (isConfirm) {$.post("../system/groupVO/deleteGroupVOById",{"groupId":id},function(data){if(data.flg){powerTable.ajax.reload();swal("", "当前操作成功 :)", "success");}else{swal("失败 :)", data.errorMsg, "error");}});} else {swal("取消", "您的操作已经取消 :)", "error");}});
	});

	//变更角色操作
	$('#roleDataTables tbody').on('click','#uptRole',function(){
		var groupId = $(this).attr("data-id");
		var groupName = $(this).attr("data-name");
		var groupMark = $(this).attr("data-desc");
		$("#roleUptInfoDiv .modal-title").html('<i class="icon-user-following"></i><span id="lblAddTitle" style="font-weight:bold"> 编辑角色基本信息</span>');
		$("#roleUptInfoDiv .modal-body").html(roleUptInfoDiv(groupId,groupName,groupMark));
		$("#roleUptInfoDiv").modal('show');
		$("#roleUptInfoForm").validate({
			errorElement: 'span',
			errorClass:'help-inline',
			focusInvalid: false,ignore: '',
			rules: {groupName: {minlength: 2,required: true,maxlength:20,
				remote:{type:'post',url:'../system/groupVO/checkGroupName',data: {groupName:function(){return $("#groupName").val();}},dataType: "json",dataFilter:function (data) {if($("#groupName").val()==groupName) return true;return  data=='false'?true:false;}}},
				roleDesc:{minlength: 2,required: true,maxlength:50}},
				messages:{groupName:{remote:'用户名已经存在请重新变更'}},
				errorPlacement: function(error,element){error.insertAfter(element);},
				highlight: function(element) {
					$(element).closest('.control-group').removeClass('success');
					$(element).closest('.help-inline').removeClass('valid');
					$(element).closest('.help-inline').removeClass('ok');
					$(element).closest('.control-group').addClass('error');
				},
				unhighlight: function(element) {$(element).closest('.control-group').removeClass('error');},
				success: function(label) {
					label.closest('.control-group').removeClass('error');
					label.closest('.control-group').addClass('success');
					label.closest('.help-inline').addClass('valid ok');
				},

				submitHandler:function(form){
					var name = $("#groupName").val();
					confirm("您确定修改["+groupName+"]群组？", 
							function(isConfirm){if (isConfirm) {
								/**
					    		 * 自定义属性
					    		 * 拼接成json对象
					    		 */
					    		var extJson = {};
					    		
//					    		extJson.bbb = "bbb";
//					    		extJson.aaa = "aaa";
					    		
					    		var extJsonStr = "groupExtJson=\""+JSON.stringify(extJson) + "\"";
					    		var postData = $("#roleUptInfoForm").serialize();
					    		
					    		var dataTT = postData+"&"+extJsonStr;
//					    		var dataTT = postData+"&"+"groupExtJson=" + extJson;
					    		
					    		console.log(extJsonStr);
					    		console.log(dataTT);
					    		
								$.post('../system/groupVO/updateGroupVOById',
										dataTT,
										function(data){
									if(data){$("#roleUptInfoDiv").modal("hide");
									powerTable.ajax.reload();
									swal("", "当前操作成功 :)", "success");
									}else{
										swal("取消", "您的操作已经取消 :)", "error");}
								});
							}else {swal("取消", "您的操作已经取消 :)", "error");}
					});
					return false;
				}});
	});
	$("#roleUptBtn").click(function(){
		$("#roleUptInfoForm").submit();
	});
	
	$('#roleDataTables tbody').on('click','#uptPerson',function(){
		var groupId = $(this).attr("data-id");
		$('#groupIdHidd').val(groupId);
		$("#personInfoDiv").modal("show");
		
		
		$('#my_multi_select1').multiSelect({
			selectableHeader: "<input type='text' placeholder='请输入搜索内容..' id='left_Btn' class='search-input'style='width: 152px;margin-bottom: 5px;'>",
			selectionHeader: "<input type='text' placeholder='请输入搜索内容..' id='right_Btn' class='search-input'style='width: 152px;margin-bottom: 5px;'>",
		});
		
		$('#my_multi_select1').multiSelect('refresh');
		$('#my_multi_select1').multiSelect('deselect_all');
		var str = ""; 
    	$.post("../system/groupVO/getThisGroupPerson",{"groupId":groupId},function(data){
    		if(data!=null){
    			pro=data.toString();
    			var strArr = data.split(",");
    			
    			$('#my_multi_select1').multiSelect({});
    			$('#my_multi_select1').multiSelect('select', strArr);
    			
    			var strArr = data.split(",")
    			$("#left_Btn").live('input propertychange',function(){
					var v=$(this).val();
					$("#ms-my_multi_select1 .ms-selectable .ms-list>li:not(.ms-selected)").filter(function(){
						return $(this).text().indexOf(v)>-1?$(this).show():$(this).hide();
					})
    			})
    			
    			$("#right_Btn").live('input propertychange',function(){
					var v=$(this).val();
					$("#ms-my_multi_select1 .ms-selection .ms-list>li.ms-selected").filter(function(){
						return $(this).text().indexOf(v)>-1?$(this).show():$(this).hide();
					})
    			})
    		}
    	});
		
	});
	
	$('#uptPersonBtn').click(function(){
		$('#uptPersonBtn').attr("disabled",true);
		var kk = $("#my_multi_select1").val();
		if(kk!=''&&kk!=undefined){
			kk = kk.toString();
		}
		$.post("../system/groupVO/updateThisGroupPerson",{"groupId":$('#groupIdHidd').val(),"userId":kk,"pro":pro},function(data){
			if(data){
				swal("成功", "操作成功！", "success");
				$("#uptPersonBtn").attr("disabled",false);
				$("#personInfoDiv").modal("hide");
			}else{
				$("#uptPersonBtn").attr("disabled",false);
				swal("取消", "操作失败！", "error");
			}
		});
	});
	
});

function crtRoleBtn2(){
	$("#roleUptInfoDiv .modal-title").html('<i class="icon-pencil"></i><span id="lblAddTitle" style="font-weight:bold"> 群组基本信息</span>');
	$("#roleUptInfoDiv .modal-body").html(roleUptInfoDiv());
	$("#roleUptInfoDiv").modal('show');
	$("#roleUptInfoForm").validate({
		errorElement: 'span',
		errorClass:'help-inline',
		focusInvalid: false,ignore: '',
		rules: {groupName: {minlength: 2,required: true,maxlength:20,
			remote:{type:'post',url:'../system/groupVO/checkGroupName',data: {groupName:function(){return $("#groupName").val();}},dataType: "json",dataFilter:function (data) {return data=='false'?true:false;}}},
			roleDesc:{minlength: 2,required: true,maxlength:50}},
			messages:{groupName:{remote:'用户名已经存在请重新变更'}},
			errorPlacement: function(error,element){error.insertAfter(element);},
			highlight: function(element) {
				$(element).closest('.control-group').removeClass('success');
				$(element).closest('.help-inline').removeClass('valid');
				$(element).closest('.help-inline').removeClass('ok');
				$(element).closest('.control-group').addClass('error');
			},
			unhighlight: function(element) {$(element).closest('.control-group').removeClass('error');},
			success: function(label) {
				label.closest('.control-group').removeClass('error');
				label.closest('.control-group').addClass('success');
				label.closest('.help-inline').addClass('valid ok');
			},
			submitHandler:function(form){
				var name = $("#groupName").val();
				confirm("您确定添加["+name+"]群组？", 
						function(isConfirm){if (isConfirm) {
							/**
				    		 * 自定义属性
				    		 * 拼接成json对象
				    		 */
				    		var extJson = {};
//				    		extJson.bbb = "bbb";
//				    		extJson.aaa = "aaa";
							//var extJsonStr = "groupExtJson="+encodeURIComponent(JSON.stringify(extJson));
				    		var extJsonStr = "groupExtJson=\""+JSON.stringify(extJson) + "\"";
//				    		var extJsonStr = "groupExtJson="+JSON.stringify(extJson);
				    		var postData = $("#roleUptInfoForm").serialize();
				    		
				    		var dataTT = postData+"&"+extJsonStr;
				    		
							$.post('../system/groupVO/saveGroupVO',
									dataTT,
									function(data){
								if(data){$("#roleUptInfoDiv").modal("hide");
								powerTable.ajax.reload();
								swal("", "当前操作成功 :)", "success");
								}else{
									swal("取消", "您的操作已经取消 :)", "error");}
							});
						}else {swal("取消", "您的操作已经取消 :)", "error");}
				});
				return false;
			}});
}